package com.geek.bams.client;

import com.geek.bams.entity.Account;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.SocketException;

public class RegisterPanel extends JPanel {
    /**
     * RegisterPanel 类中持有 ATMClient 的引用
     * 通过构造函数传入 ATMClient 实例并保存在私有成员变量 atm 中
     * RegisterPanel 依赖于 ATMClient 来完成注册业务逻辑，如调用 atm.bank.register() 方法
     * 这体现了"部分-整体"的关系，RegisterPanel 是整体的一部分，ATMClient 是其运行所需的组件
     * 因此这是典型的组合关系，表示 RegisterPanel 组合了 ATMClient 功能。
     */
    private ATMClient atm;
    public RegisterPanel( ATMClient atm) {
        this.atm = atm;
        initComponents();
    }
    /*//跳转至BusinessPanel界面
    private void submit(ActionEvent e) {
        CardLayout cardLayout = (CardLayout)this.getParent().getLayout();
        cardLayout.show(this.getParent() , "businessPanel");

    }*/

    // 密码校验，6位，只能是数字，不符合就置空
    private boolean validatePassword(String password) {
        if (password.length() != 6 || !password.matches("[0-9]+")) {
            passwordField.setText("");
            JOptionPane.showMessageDialog(null, "密码长度为6位，只能是数字");
            return false;
        }
        return true;
    }

    // 密码一致性校验
    private boolean validatePasswordConfirmation(String password, String repassword) {
        if (!password.equals(repassword)) {
            passwordField.setText("");
            repasswordField.setText("");
            JOptionPane.showMessageDialog(null, "密码不一致");
            return false;
        }
        return true;
    }

    // 身份证号校验，正则判断，需要18位，不符合就置空
    private boolean validatePersonId(String personId) {
        if (!personId.matches("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$")) {
            personIdTextField.setText("");
            JOptionPane.showMessageDialog(null, "身份证号格式不正确");
            return false;
        }
        return true;
    }

    // 邮箱校验，正则校验，不符合就置空
    private boolean validateEmail(String mail) {
        if (!mail.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")) {
            mailTextField.setText("");
            JOptionPane.showMessageDialog(null, "邮箱格式不正确");
            return false;
        }
        return true;
    }

    //提交注册信息，跳转至BusinessPanel界面
    private void submit(ActionEvent e) {
        // 收集页面数据
        String name = nameTextField.getText().trim();
        String password = new String(passwordField.getPassword());
        String repassword = new String(repasswordField.getPassword());
        String personId = personIdTextField.getText().trim();
        String addr = addrTextField.getText().trim();
        String mail = mailTextField.getText().trim();
        int type = comboBox.getSelectedIndex();

        // 数据校验
        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(null, "用户名不能为空");
            return;
        }

        if (!validatePassword(password)) return;
        if (!validatePasswordConfirmation(password, repassword)) return;
        if (!validatePersonId(personId)) return;
        if (!validateEmail(mail)) return;

        /*//未加入网络编程  begin
        // 调用Bank银行业务（本地调用）
        try {
            Account account = atm.bank.register(password, repassword, name, personId, mail, type);
            // 开户成功
            if (account != null) {
                // 1.初始化BusinessPanel界面
                atm.account = account;
                atm.businessPanel.initBusiness();

                // 2.跳转至BusinessPanel界面
                CardLayout cardLayout = (CardLayout) this.getParent().getLayout();
                cardLayout.show(this.getParent(), "businessPanel");

                // 3.清空注册界面数据
                clearRegister();
            }
        } catch (Exception ex) {
            // 开户失败
            // 1.弹窗提醒失败信息
            JOptionPane.showMessageDialog(null, ex.getMessage());
            // 2.清空密码相关的输入框
            passwordField.setText("");
            repasswordField.setText("");
        }
        //未加入网络编程  end*/

        //==================加入网络编程后  begin
        //1.发送指令   写PrintWriter
        atm.pw.println("register#" + password + "#" + repassword + "#" + name + "#" + personId + "#" + mail + "#" + type);
        atm.pw.flush();

        //4.等待服务器发送的结果  读ObjectInputStream
        try {
            Object o = atm.ois.readObject();

            if (o instanceof Account) {
                //登录成功，跳转至业务界面，初始化业务界面中数据
                Account acc = (Account) o;
                if (acc != null) {
                    //JOptionPane.showMessageDialog(this , "登录成功");
                    //跳转至业务界面
                    CardLayout cardLayout = (CardLayout) this.getParent().getLayout();
                    cardLayout.show(this.getParent(), "businessPanel");
                    //初始化业务界面中数据
                    atm.account = acc;
                    atm.businessPanel.initBusiness();
                    //清空注册界面
                    clearRegister();
                }
            } else if (o instanceof String) {
                //这侧失败，弹框异常信息，并清空每一个框
                JOptionPane.showMessageDialog(this, o);
                clearRegister();
            }
        } catch (SocketException ex) {
            JOptionPane.showMessageDialog(this, "服务器已关闭");
            System.exit(0);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex);
        }
        //==================加入网络编程后  end
    }

    //清空注册界面
    public void clearRegister(){
        nameTextField.setText("");
        passwordField.setText("");
        repasswordField.setText("");
        personIdTextField.setText("");
        addrTextField.setText("");
        mailTextField.setText("");
    }

    //返回主页面
    private void back(ActionEvent e) {
        CardLayout cardLayout = (CardLayout)this.getParent().getLayout();
        cardLayout.show(this.getParent() , "mainPanel");
    }


    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        label1 = new JLabel();
        label2 = new JLabel();
        label3 = new JLabel();
        label4 = new JLabel();
        label5 = new JLabel();
        label6 = new JLabel();
        label7 = new JLabel();
        label8 = new JLabel();
        label9 = new JLabel();
        label10 = new JLabel();
        label11 = new JLabel();
        label12 = new JLabel();
        comboBox = new JComboBox<>();
        nameTextField = new JTextField();
        personIdTextField = new JTextField();
        addrTextField = new JTextField();
        mailTextField = new JTextField();
        submitButton = new JButton();
        backButton = new JButton();
        label13 = new JLabel();
        passwordField = new JPasswordField();
        repasswordField = new JPasswordField();

        //======== this ========
        setLayout(null);

        //---- label1 ----
        label1.setText("text");
        add(label1);
        label1.setBounds(75, 40, 0, 115);
        add(label2);
        label2.setBounds(65, 5, label2.getPreferredSize().width, 35);

        //---- label3 ----
        label3.setText("text");
        add(label3);
        label3.setBounds(75, 135, 0, 0);

        //---- label4 ----
        label4.setText("text");
        add(label4);
        label4.setBounds(120, 165, 0, 5);

        //---- label5 ----
        label5.setText("text");
        add(label5);
        label5.setBounds(70, 120, 0, 0);

        //---- label6 ----
        label6.setText("\u7528 \u6237 \u540d:");
        label6.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        add(label6);
        label6.setBounds(90, 130, 90, 30);

        //---- label7 ----
        label7.setText("\u8d26\u6237\u7c7b\u578b\uff1a");
        label7.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        add(label7);
        label7.setBounds(90, 70, 90, 30);

        //---- label8 ----
        label8.setText(" \u5bc6    \u7801:");
        label8.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        add(label8);
        label8.setBounds(90, 190, 90, 30);

        //---- label9 ----
        label9.setText("\u786e\u8ba4\u5bc6\u7801:");
        label9.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        add(label9);
        label9.setBounds(90, 250, 90, 30);

        //---- label10 ----
        label10.setText("\u8eab\u4efd\u8bc1\u53f7\u7801:");
        label10.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        add(label10);
        label10.setBounds(90, 310, 90, 30);

        //---- label11 ----
        label11.setText("\u8be6\u7ec6\u5730\u5740:");
        label11.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        add(label11);
        label11.setBounds(90, 370, 90, 30);

        //---- label12 ----
        label12.setText("E-Mail:");
        label12.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        add(label12);
        label12.setBounds(95, 430, 90, 30);

        //---- comboBox ----
        comboBox.setModel(new DefaultComboBoxModel<>(new String[] {
            "\u50a8\u84c4\u8d26\u6237",
            "\u4fe1\u7528\u8d26\u6237",
            "\u53ef\u8d37\u6b3e\u7684\u50a8\u84c4\u8d26\u6237",
            "\u53ef\u8d37\u6b3e\u7684\u4fe1\u7528\u8d26\u6237"
        }));
        add(comboBox);
        comboBox.setBounds(205, 70, 185, comboBox.getPreferredSize().height);
        add(nameTextField);
        nameTextField.setBounds(205, 130, 190, 40);
        add(personIdTextField);
        personIdTextField.setBounds(205, 310, 190, 40);
        add(addrTextField);
        addrTextField.setBounds(205, 370, 190, 40);
        add(mailTextField);
        mailTextField.setBounds(205, 430, 190, 40);

        //---- submitButton ----
        submitButton.setText("\u63d0\u4ea4");
        submitButton.addActionListener(e -> submit(e));
        add(submitButton);
        submitButton.setBounds(90, 510, 80, 40);

        //---- backButton ----
        backButton.setText("\u8fd4\u56de");
        backButton.addActionListener(e -> back(e));
        add(backButton);
        backButton.setBounds(315, 510, 80, 40);

        //---- label13 ----
        label13.setText("\u6ce8\u518c\u9875\u9762");
        label13.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 24));
        add(label13);
        label13.setBounds(new Rectangle(new Point(185, 20), label13.getPreferredSize()));
        add(passwordField);
        passwordField.setBounds(205, 190, 190, 40);
        add(repasswordField);
        repasswordField.setBounds(205, 250, 190, 40);

        setPreferredSize(new Dimension(500, 650));
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JLabel label4;
    private JLabel label5;
    private JLabel label6;
    private JLabel label7;
    private JLabel label8;
    private JLabel label9;
    private JLabel label10;
    private JLabel label11;
    private JLabel label12;
    private JComboBox<String> comboBox;
    private JTextField nameTextField;
    private JTextField personIdTextField;
    private JTextField addrTextField;
    private JTextField mailTextField;
    private JButton submitButton;
    private JButton backButton;
    private JLabel label13;
    private JPasswordField passwordField;
    private JPasswordField repasswordField;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
